#!/Users/michael/anaconda3/bin/python

"""
定投 BTC, ETH, ICP, DOGE 四种货币
每个月1000RMB
根据近一个月跌幅分配投资份额
输入参数:
BTC 57000 3600, ETH ...
即币种、上个月1号价格(收盘价)、上个月最后一天价格(收盘价)，
然后逗号隔开，单位均为 USDT

以 250 为基准线，如果一个币涨跌幅为0，则投250，
如果涨跌幅 >0 则涨得越多投得越少
如果涨跌幅 <0 则跌得越多投得越多
"""

# raw_prices = 'BTC 57366.32 37776.4, ETH 2865.9 2535.49, ICP 410.98 116.87, DOGE 0.358994 0.316154'
raw_prices = 'BTC 57856.334 37319.65129771365, ETH 2949.13636522429 2708.9656529509743, FTM 0.8073303528181069 0.3206416885218926, THETA 11.481127238576994 7.133070822372314, DOGE 0.39357488560000004 0.325605203613536, ICP 313.22489242646475 114.79397391297455'

monthly_investment = 162.45 # 每个月能投入的值

class Crypto:

    def __init__(self, name, open_price, close_price):
        self.name = name
        self.open_price = open_price
        self.close_price = close_price
        self.relative_distance = None
        self.relative_amount = None

    @property
    def distance(self):
        return (self.close_price - self.open_price) / self.open_price


def set_relative_distance(cryptos):
    total_distance = 0
    for crypto in cryptos:
        total_distance += abs(crypto.distance)
    for crypto in cryptos:
        crypto.relative_distance = crypto.distance / total_distance


cryptos = []
for info in raw_prices.split(','):
    name, open_price, close_price = info.strip().split()
    crypto = Crypto(name=name, open_price=float(open_price), close_price=float(close_price))
    cryptos.append(crypto)

set_relative_distance(cryptos)
crypto_num = len(cryptos)

print('本月总投入: {:.2f} USDT (不浮动)，基础值为 {:.2f} USDT，拆分如下:\n'.format(monthly_investment, monthly_investment / crypto_num))

total_investment = 0
for crypto in cryptos:
    crypto.relative_amount = (1 - crypto.relative_distance) * (monthly_investment / crypto_num)
    print('{:<4} 月相对变化率: {:>6.2f}%, 相对值 {:>6.2f} USDT (相对基础值波动: {:>6.2f})'.format(
        crypto.name, 
        crypto.relative_distance * 100, 
        crypto.relative_amount,
        crypto.relative_amount - monthly_investment / crypto_num
    ))

    total_investment += crypto.relative_amount

print('\n最终分摊规则:\n')
for crypto in cryptos:
    print('{:<4}: {:>6.2f} USDT'.format(crypto.name, (crypto.relative_amount / total_investment) * monthly_investment))
    
